class Cache {
    constructor (prefix) {
        this.prefix = prefix
        try {
            this.keys = JSON.parse(localStorage.getItem('cache-keys'))
            if (!this.keys) {
                this.keys = []
            }
        } catch (e) {
            this.keys = []
        }
    }

    addKey (key) {
        if (this.keys.indexOf(key) === -1) {
            this.keys.push(key)
            localStorage.setItem('cache-keys', JSON.stringify(this.keys))
        }
    }

    rmKey (key) {
        this.keys.splice(this.keys.indexOf(key), 1)
        localStorage.setItem('cache-keys', JSON.stringify(this.keys))
    }

    /**
     * 获取全部键值
     */
    getAll () {
        let objs = {}
        for (let key of this.keys) {
            objs[ley] = this.get(key)
        }
        return objs
    }

    /**
     * 删除全部
     */
    clearAll () {
        for (let key of this.keys) {
            localStorage.removeItem(this.prefix + key)
        }
        this.keys = []
        localStorage.removeItem('cache-keys')
    }

    /**
     * 是否存在
     * @param key
     * @returns {*}
     */
    has (key) {
        try {
            const obj = JSON.parse(localStorage.getItem(this.prefix + key))
            if (!obj) {
                return false
            }
            if (obj.e > 0 && obj.e < new Date().getTime()) {
                this.remove(key)
                return false
            }
            return true
        } catch (e) {
            return false
        }
    }

    /**
     * 获取值
     * @param key
     */
    get (key) {
        if (this.has(key)) {
            const obj = JSON.parse(localStorage.getItem(this.prefix + key))
            return obj.s
        } else {
            return null
        }
    }

    /**
     * 设置值
     * @param key
     * @param value
     * @param exp
     */
    set (key, value, exp = 0) {
        if (exp > 0) {
            exp = new Date().getTime() + exp * 1000
        }
        this.addKey(key)
        localStorage.setItem(this.prefix + key, JSON.stringify({
            e: exp,
            s: value
        }))
    }

    /**
     * 删除值
     * @param key
     */
    remove (key) {
        localStorage.removeItem(this.prefix + key)
        this.rmKey(key)
        if (this.keys.length === 0) {
            localStorage.removeItem('cache-keys')
        }
    }
}

export default Cache
